package com.tanxi521.afkreward.data;

import com.tanxi521.afkreward.AfkReward;
import com.tanxi521.afkreward.util.ConfigUtil;
import org.bukkit.ChatColor;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;

public class ConnectPool {

    // 连接池容量初始化
    public final static ArrayBlockingQueue<Connection> pool =
            new ArrayBlockingQueue<>(ConfigUtil.getPoolSize());

    // 正在使用的连接数量
    public static Integer using = 0;

    public static Integer init = 0;

    public static String url = ConfigUtil.getMysqlUrl();
    public static String mysqlPort = ConfigUtil.getMysqlPort();
    public static String mysqlUser = ConfigUtil.getMysqlUser();
    public static String mysqlPassword = ConfigUtil.getMysqlPassword();
    public static String mysqlDatabase = ConfigUtil.getMysqlDatabase();

    // 初始化连接池Mysql
    public static void initPoolMysql() {
        AfkReward.getInstance().getLogger().info("§2使用Mysql,正在初始化MYSQL连接池");
        long start = new Date().getTime();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String mysqlUrl = "jdbc:mysql://" + url + ":" + mysqlPort + "/" + mysqlDatabase +
                    "?serverTimezone=Asia/Shanghai&useUnicode=true" +
                    "&characterEncoding=UTF-8&useSSL=false";
            for (int i = 0; i < ConfigUtil.getPoolSize(); i++) {
                Connection connection = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
                pool.add(connection);
                init++;
            }
            AfkReward.getInstance().getLogger().info(ChatColor.GREEN + "初始化连接池成功,耗时: " + (new Date().getTime() - start) + " ms");
        } catch (Exception e) {
            e.printStackTrace();
            AfkReward.getInstance().getLogger().warning("§c数据库连接失败，请检查配置文件");
            AfkReward.getInstance().getServer().getPluginManager().disablePlugin(AfkReward.getInstance());
        }
    }

    // 初始化连接池SQLITE
    public static void initPoolSQLITE() {
        try {
            AfkReward.getInstance().getLogger().info("§2使用本地存储,正在初始化本地连接池");
            Class.forName("com.mysql.jdbc.Driver");
            String databaseName = "afk_reward";
            File file = new File("plugins/AfkReward/data");
            if (!file.exists() && !file.isDirectory()) {
                //不存在
                file.mkdir();
            }
            for (int i = 0; i < ConfigUtil.getPoolSize(); i++) {
                Connection connection = DriverManager.getConnection("jdbc:sqlite:plugins/AfkReward/data/" + databaseName + ".db");
                pool.add(connection);
            }
            AfkReward.getInstance().getLogger().info(ChatColor.GREEN + "初始化连接池成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initConnection() {
        if (ConfigUtil.isMysql()) initPoolMysql();
        else initPoolSQLITE();
    }

    public static Connection getConnection() {
        try {
            using++;
            init--;
            return pool.take();
        } catch (InterruptedException e) {
            using--;
            init++;
            e.printStackTrace();
        }
        return null;
    }

    public static void returnSource(Connection connection) {
        try {
            using--;
            init++;
            pool.put(connection);
        } catch (InterruptedException e) {
            using++;
            init--;
            e.printStackTrace();
        }
    }

    public static void close(ArrayBlockingQueue<Connection> pool) {
        AfkReward.getInstance().getLogger().info(ChatColor.GREEN + "正在释放连接池");
        long start = System.currentTimeMillis();
        while (true) {
            Connection connection = pool.poll();
            if (connection == null) {
                break;
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        AfkReward.getInstance().getLogger().info(ChatColor.GREEN + "成功释放连接,耗时" +
                (System.currentTimeMillis() - start) + "ms");
    }


}
